package com.example.imserver.service;

import com.example.imserver.entity.Contact;
import com.example.imserver.entity.User;
import com.example.imserver.repository.ContactRepository;
import com.example.imserver.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ContactService {
    @Autowired
    private ContactRepository contactRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    public List<Contact> getUserContacts(Long userId) {
        return contactRepository.findByUserId(userId);
    }
    
    public List<Map<String, Object>> getUserContactsWithInfo(Long userId) {
        List<Contact> contacts = contactRepository.findByUserId(userId);
        return contacts.stream().map(contact -> {
            Map<String, Object> contactMap = new HashMap<>();
            contactMap.put("id", contact.getId());
            contactMap.put("userId", contact.getUserId());
            contactMap.put("contactId", contact.getContactId());
            contactMap.put("status", contact.getStatus());
            contactMap.put("createdAt", contact.getCreatedAt());
            
            // 获取联系人详细信息
            Optional<User> contactUser = userRepository.findById(contact.getContactId());
            if (contactUser.isPresent()) {
                User user = contactUser.get();
                contactMap.put("nickname", user.getNickname());
                contactMap.put("avatar", user.getAvatar());
                contactMap.put("username", user.getUsername());
            } else {
                contactMap.put("nickname", null);
                contactMap.put("avatar", null);
                contactMap.put("username", null);
            }
            
            return contactMap;
        }).collect(Collectors.toList());
    }
    
    @Transactional
    public Map<String, Object> addContactRequest(Long userId, String qrCode) {
        Map<String, Object> result = new HashMap<>();
        
        // 从二维码解析出用户ID或用户名
        User contactUser = userRepository.findByUsername(qrCode.replace("QR_", "").split("_")[0])
                .orElse(null);
        
        if (contactUser == null || contactUser.getId().equals(userId)) {
            result.put("success", false);
            result.put("message", "无效的二维码");
            return result;
        }
        
        // 检查是否已经是联系人
        Optional<Contact> existing = contactRepository.findContactRelation(userId, contactUser.getId());
        if (existing.isPresent() && "ACCEPTED".equals(existing.get().getStatus())) {
            result.put("success", false);
            result.put("message", "已经是联系人");
            return result;
        }
        
        // 创建或更新联系人请求
        Contact contact = existing.orElse(new Contact());
        contact.setUserId(userId);
        contact.setContactId(contactUser.getId());
        contact.setStatus("PENDING");
        
        contactRepository.save(contact);
        
        result.put("success", true);
        result.put("message", "已发送添加请求");
        return result;
    }
    
    @Transactional
    public void acceptContactRequest(Long requestId, Long userId) {
        Contact contact = contactRepository.findById(requestId)
                .orElseThrow(() -> new RuntimeException("请求不存在"));
        
        if (!contact.getContactId().equals(userId)) {
            throw new RuntimeException("无权操作");
        }
        
        contact.setStatus("ACCEPTED");
        contactRepository.save(contact);
        
        // 创建反向联系人关系
        Contact reverseContact = new Contact();
        reverseContact.setUserId(contact.getContactId());
        reverseContact.setContactId(contact.getUserId());
        reverseContact.setStatus("ACCEPTED");
        contactRepository.save(reverseContact);
    }
    
    @Transactional
    public void deleteContact(Long userId, Long contactId) {
        contactRepository.findContactRelation(userId, contactId).ifPresent(contact -> {
            contactRepository.delete(contact);
        });
        contactRepository.findContactRelation(contactId, userId).ifPresent(contact -> {
            contactRepository.delete(contact);
        });
    }
    
    public List<Contact> getPendingRequests(Long userId) {
        return contactRepository.findPendingRequests(userId);
    }
}

